import { isString, isUndefined, map } from "lodash";
import React, { useState, useEffect } from "react";
import { Section, Input, Select, ContextHelp } from "@/components/visualizations/editor";
import JsonViewInteractive from "@/components/json-view-interactive/JsonViewInteractive";
import { visualizationsSettings } from "@/visualizations/visualizationsSettings";
import { axios } from "@/services/axios";

function Editor({ column, onChange }) {
  const [enums, setEnums] = useState([]);

  useEffect(() => {
    axios.get("api/enums/all").then((mapResults) => {
      setEnums(mapResults);
    })
  }, []);

  return enums && enums.length>0 && (
    <React.Fragment>
    <Section>
      <Select
        label="显示样式"
        defaultValue={column.selectDisplay || ''}
        onChange={value => onChange({ selectDisplay: value })}
      >
        <Select.Option value="">下拉选择</Select.Option>
        <Select.Option value="option">按钮选择</Select.Option>
        <Select.Option value="button">开关选择</Select.Option>
      </Select>
    </Section>
    <Section>
      <Select
        label="选择枚举"
        defaultValue={column.enums_code}
        showSearch
        optionFilterProp="label"
        onChange={value => onChange({ enums_code: value })}
      >
        {map(enums, q => (
          <Select.Option value={q.code}>{q.name}</Select.Option>
        ))}
      </Select>
    </Section>
    <Section>
      <Input
        label={
          <React.Fragment>
            默认值
            <ContextHelp.FunctionFormatSpecs />
          </React.Fragment>
        }
        defaultValue={column.defaultValue}
        onChange={event => onChange({ defaultValue: event.target.value })}
      />
    </Section>
    </React.Fragment>
  );
}

export default function initEnumsColumn(column) {
  function prepareData(row) {
    const text = row[column.name];
    if (isString(text) && text.length <= visualizationsSettings.tableCellMaxJSONSize) {
      try {
        return { text, value: JSON.parse(text) };
      } catch (e) {
        // ignore `JSON.parse` error and return default value
      }
    }
    return { text, value: undefined };
  }

  function JsonColumn({ row }) {
    // eslint-disable-line react/prop-types
    const { text, value } = prepareData(row);
    if (isUndefined(value)) {
      return <div className="json-cell-invalid">{"" + text}</div>;
    }

    return (
      <div className="json-cell-valid">
        <JsonViewInteractive value={value} />
      </div>
    );
  }

  JsonColumn.prepareData = prepareData;

  return JsonColumn;
}

initEnumsColumn.friendlyName = "枚举";
initEnumsColumn.Editor = Editor;
